__author__ = 'XY'

import ftplib


def parseUrl(url):
    proto, path = url.split("//")
    items = path.split("/")
    domain = items[0]
    directory = "/" + "/".join(items[1:len(items) - 1])
    fileName = items[-1]
    return domain, directory, fileName


def retrive(remoteFile, localFile, userName, password):
    domain, directory, fileName = parseUrl(remoteFile)
    try:
        ftp = ftplib.FTP(domain)
        ftp.login(userName, password)
        ftp.cwd(directory)
    except:
        return 1, "Unable to login"
    try:
        fileHandle = open(localFile, "wb")
        ftp.retrbinary("RETR " + fileName, fileHandle.write)
        fileHandle.close()
    except:
        return 2, "File {0} does not exist".format(fileName)
    finally:
        ftp.close()
    return 0


if __name__ == "__main__":
    print(retrive("ftp://down.licai668.cn/pwr/tb_pwr_full_20150818.csv", r"D:\\a.csv", "fafaly281", "gg20150810mm"))